<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <div id="box"></div>
    <script>

        let ajax = {
            get:function(url,data,callBack){
                //data= {name:"王哥",age="22"} => ?name=王哥&age=22
                let x = new XMLHttpRequest();
                // console.log(Object.keys(data)); //['name', 'age']
                let arr = Object.keys(data).map(item=>`${item}=${data[item]}&`);
                // console.log(arr); //['name=王哥&', 'age=22&']
                let str = arr.join(''); 
                // console.log(str); //name=王哥&age=22&
                str = str.slice(0,-1);
                // console.log(str); //name=王哥&age=22

                // console.log(url+'?'+str); //http://localhost/ajaxserver?name=王哥&age=22
                x.open('get',url+'?'+str);
                x.send();
                x.responseType='json';
                x.onreadystatechange=function(){
                    if(x.readyState === 4 && x.status === 200){
                        callBack(x.response);
                    }
                }
            },
            post:function(url,data,callBack){
                let x = new XMLHttpRequest();
                x.open('post',url);
                x.send();
                x.responseType='json';
                x.onreadystatechange=function(){
                    if(x.readyState === 4 && x.status === 200){
                        callBack(x.response);
                    }
                }
            }
        }


        let box = document.querySelector('#box');
        window.onload = function(){

            ajax.get('http://localhost/ajaxserver',{name:"王哥",age:"22"},function(data){
                console.log(data);
                // let obj = JSON.parse(data);
                box.innerHTML = `姓名：${data.name}，年龄：${data.age}`;
            })

            // ajax.post('http://localhost/ajaxserverpost',{},function(data){
            //     // console.log(data);
            //     box.innerHTML = `姓名：${data.name}，年龄：${data.age}`;
            // })
        }
    </script>
</body>
</html>